package com.hyfrogx.modules.app.controller.zoom;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.log.LogEnum;
import com.hyfrogx.common.log.LogUtils;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.validator.ValidatorUtils;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.StringUtils;
import com.hyfrogx.modules.manage.entity.HyProductionScaleEntity;
import com.hyfrogx.modules.manage.service.HyProductionVacuateService;
import com.hyfrogx.modules.zoom.entity.HyPowerUser;
import com.hyfrogx.modules.zoom.entity.HyVipMeetConfig;
import com.hyfrogx.modules.zoom.entity.HyZoomHistory;
import com.hyfrogx.modules.zoom.entity.HyZoomMeeting;
import com.hyfrogx.modules.zoom.form.ZoomHistoryForm;
import com.hyfrogx.modules.zoom.param.MeetpriceType;
import com.hyfrogx.modules.zoom.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author ：Li9527
 * @date ：Created in 2019-04-03 10:20
 * @description：客户端会议历史记录控制类
 * @modified By：
 * @version: 1.0
 */
@RestController
@RequestMapping("api/zoom/history")
@Api(value = "参会历史记录生成及获取controller", tags = "客户端--参会历史记录生成及获取")
public class ApiZoomHistoryController {

    @Autowired
    HyZoomHistoryService historyService;

    @Autowired
    HyZoomMeetingService meetingService;

    @Autowired
    UserService userService;

    @Autowired
    HyZoomDetailService hyZoomDetailService;

    @Autowired
    MeetPriceService meetPriceService;

    @Autowired
    MeetJoinPriceService meetJoinPriceService;

    @Autowired
    HyVipMeetConfigService vipMeetConfigService;

    @Autowired
    HyPowerUserService powerUserService;

    @Autowired
    HyProductionVacuateService hyProductionVacuateService;

    Logger zoomJoinInfoLog = LogUtils.Logger(LogEnum.ZOOM_JOIN_INFO_LOGS);

    /**
     * 记日志/扣款/生成记录/判断有无支付
     *
     * @param form
     */
    @Login
    @PostMapping("addMeetJoin")
    @ApiOperation("记日志/扣款/生成记录")
    public R addMeetJoin(@RequestBody ZoomHistoryForm form,
                         @ApiIgnore @RequestAttribute("userId") Long uid,
                         @ApiIgnore @RequestAttribute("userIp") String userIp) {
        ValidatorUtils.validateClientEntity(form);
        // 通过会议室主键id<形参zoomid>获取会议室对象
        HyZoomMeeting zoomMeeting = meetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("zoomId", form.getZoomId()));
        if (zoomMeeting == null) {
            return R.error("会议不存在");
        }
        // 通过会议室真实<Zoom接口返回的会议室id>判断是否存在过该条会议室记录
        HyZoomHistory joinHistory = historyService.getOne(new QueryWrapper<HyZoomHistory>().eq("true_meet_id", form.getZoomId()).like("join_id",form.getJoinId()));
        if (ObjectUtil.isNotNull(joinHistory)) {
            return R.error("已生成记录");
        }
        // 记日志
        User user = userService.getById(uid);
        zoomJoinInfoLog.info("用户网段" + userIp + ";----用户uid：" + uid + ";-----用户手机号：" + user.getPhone() + ";---加入了会议id：" + zoomMeeting.getZoomid());
        // 记录会议用户一对一关系/只记参会者即可,因为开会者就在history对象中,参会者咋detail对象中,可取出参会人数及集合
        HyZoomHistory oldHistory = historyService.getOne(new QueryWrapper<HyZoomHistory>().eq("true_meet_id", form.getZoomId()));
        // 如果不存在,新增该记录
        if (oldHistory == null) {
            HyZoomHistory hyZoomHistory = new HyZoomHistory();
            BeanUtils.copyProperties(form, hyZoomHistory);
            hyZoomHistory.setCreateDate(new Date());
            hyZoomHistory.setTrueMeetId(zoomMeeting.getZoomid());
            // 设置会议室主题
            hyZoomHistory.setTopic(zoomMeeting.getLocalname());
            hyZoomHistory.setMeetingCapacity(zoomMeeting.getMeetingcapacity());
            // 参会人员及门票
            if(form.getJoinId().equals(form.getHostId())){
                hyZoomHistory.setJoinId("-0");
                hyZoomHistory.setAlleran(0);
            }else {
                hyZoomHistory.setJoinId(form.getJoinId().toString());
                hyZoomHistory.setAlleran(zoomMeeting.getPrice());
            }
            hyZoomHistory.setSysjoinpay(0);
            // 设置参会时系统收费价格
            if (zoomMeeting.getIsvipzoom() == 1) {
                HyVipMeetConfig hyVipMeetConfig = vipMeetConfigService.getOne(new QueryWrapper<HyVipMeetConfig>().eq("capacity", zoomMeeting.getMeetingcapacity()));
                hyZoomHistory.setSysjoinpay(Integer.valueOf(hyVipMeetConfig.getPrice()));
            }
            if (zoomMeeting.getIsvipzoom() == 0) {
                hyZoomHistory.setSysjoinpay(meetingService.getJoinBasicMeetNeedpay(zoomMeeting));
            }
            hyZoomHistory.setCharge(0);
            if (zoomMeeting.getPrice() > 0) {
                hyZoomHistory.setCharge(1);
                hyZoomHistory.setPrice(zoomMeeting.getPrice());
            }
            // 会议室密码
            hyZoomHistory.setHavePsd(0);
            if (zoomMeeting.getPassword() != null && StringUtils.isNotBlank(zoomMeeting.getPassword())) {
                hyZoomHistory.setHavePsd(1);
                hyZoomHistory.setPassword(zoomMeeting.getPassword());
            }
            // 会议室类型
            hyZoomHistory.setMtype(zoomMeeting.getIsvipzoom());
            if (zoomMeeting.getIsvipzoom() != 1) {
                // 会议持续时长
                hyZoomHistory.setTime(zoomMeeting.getTime());
            } else {
                hyZoomHistory.setTime(0);
            }
            // 根据会议持续时长和会议室规模取到会议室收费,只有常规会议室，并且没有被预约才收
            if (zoomMeeting.getReserveUid() == null && zoomMeeting.getIsvipzoom() == 0) {
                // 先检查该用户该规格是否拥有特权卡。特权卡是否超过有效期
                HyPowerUser powerUser = powerUserService.getOne(new QueryWrapper<HyPowerUser>().eq(
                        "capacity", zoomMeeting.getMeetingcapacity()).eq("uid", zoomMeeting.getCurrentuid()).eq("type", FrogConstant.ZoomMeetType.COMMEN));
                if (powerUser != null && powerUser.getEnddate().getTime() > System.currentTimeMillis()) {
                    // 拥有权益并且有效
                    hyZoomHistory.setNeedpay(0);
                    hyZoomHistory.setTruepay(0);
                } else {
                    int charge = meetingService.getNeedpay(zoomMeeting);
                    hyZoomHistory.setNeedpay(charge);
                    hyZoomHistory.setTruepay(charge);
                }
            } else {
                hyZoomHistory.setNeedpay(0);
                hyZoomHistory.setTruepay(0);
            }
            // 新增会议记录对象
            Boolean result = historyService.save(hyZoomHistory);
            if (result) {
                return R.ok("新增成功");
            } else {
                return R.error("新增失败");
            }
        } // 如果存在,拼接上新的参会者
        else {
            // 将原来的该次会议对象查出来,加上新的会议参与者
            oldHistory.setJoinId(oldHistory.getJoinId() + ";" + form.getJoinId());
            // 设置收费金额
            oldHistory.setAlleran(oldHistory.getAlleran() + zoomMeeting.getPrice());
            if (zoomMeeting.getIsvipzoom() != 2) {
                // 设置参会系统扣费
                oldHistory.setAllsysjoinpay(oldHistory.getAllsysjoinpay() + oldHistory.getSysjoinpay());
            } else {
                // 体验会议室没有参会系统扣费的说法
                oldHistory.setAllsysjoinpay(0);
            }
            if (zoomMeeting.getIsvipzoom() != 1) {
                // 获取普通会议参会抽成基数及比例
                HyProductionScaleEntity comenScale = hyProductionVacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>().eq("param_key",FrogConstant.SysConfigKey.COMMEN_MEET_CARD));
                // 如果收费情况比当时的门票抽成基准值大,计算抽成,否则抽成的默认值就是0
                if (zoomMeeting.getPrice() >= comenScale.getBasePrice().intValue()) {
                    int true_price = (int) Math.floor((double) zoomMeeting.getPrice() * (100 - comenScale.getScale()) / 100);
                    int precentCoin = zoomMeeting.getPrice() - true_price;
                    oldHistory.setPercentcoin(oldHistory.getPercentcoin() + precentCoin);
                }
            } else {
                // 获取专属会议参会抽成基数及比例
                HyProductionScaleEntity vipScale = hyProductionVacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>().eq("param_key",FrogConstant.SysConfigKey.VIP_MEET_CARD));
                if (zoomMeeting.getPrice() >= vipScale.getBasePrice().intValue()) {
                    int true_price = (int) Math.floor((double) zoomMeeting.getPrice() * (100 - vipScale.getScale()) / 100);
                    int precentCoin = zoomMeeting.getPrice() - true_price;
                    oldHistory.setPercentcoin(oldHistory.getPercentcoin() + precentCoin);
                }
            }
            Boolean result = historyService.updateById(oldHistory);
            if (result) {
                return R.ok("拼接成功");
            } else {
                return R.error("拼接失败");
            }
        }


    }

    /**
     * 分页获取我的开会记录
     *
     * @param params
     * @param uid
     */
    @Login
    @PostMapping("getMyOpenHistory")
    @ApiOperation("分页获取我的开会记录")
    public R getMyOpenHistory(@RequestParam Map<String, Object> params,
                              @RequestParam(value = "uid", required = true) Integer uid) {
        // 获取是否有专属会议室
        params.put("orderByField", "create_date");
        params.put("isAsc", false);
        params.put("hostId", uid);
        Page page = historyService.selectPageByConditions(new QueryExt(params));
        return R.ok().put("page", page);
    }

    /**
     * 分页获取我的参会记录
     *
     * @param params
     * @param uid
     */
    @Login
    @PostMapping("getMyJoinHistory")
    @ApiOperation("分页获取我的参会记录")
    public R getMyJoinHistory(@RequestParam Map<String, Object> params,
                              @RequestParam(value = "uid", required = true) Integer uid) {
        // 获取是否有专属会议室
        params.put("orderByField", "create_date");
        params.put("isAsc", false);
        params.put("joinId", uid);
        Page page = historyService.selectPageByConditions(new QueryExt<>(params));
        return R.ok().put("page", page);
    }


}
